package com.gugee.tiktok.data.consumer.music.monitor;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
// @Component
public class MonitorAop {

    @Pointcut(value = "@annotation(com.gugee.tiktok.data.consumer.music.monitor.Monitor)")
    public void Pointcut(){
    }

    @Around(value = "Pointcut()")
    public Object printInfo(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Monitor monitor = getMethod(proceedingJoinPoint).getAnnotation(Monitor.class);
        long startTime = System.currentTimeMillis();

        try{
            return proceedingJoinPoint.proceed();
        }finally {
            if(monitor.maxTime() > 0){
                long useTime = (System.currentTimeMillis() -startTime)/1000;
                if (monitor.timeUnit() == Monitor.TimeUnit.SECOND) {
                    if (useTime >= monitor.maxTime()){
                        log.info(monitor.value()+",用时: {}秒",useTime);
                    }
                }else if(monitor.timeUnit() == Monitor.TimeUnit.MINUTE){
                    double minute = ((int)((useTime/60.0)*10)/10.0);
                    if (minute >= monitor.maxTime()){
                        log.info(monitor.value()+",用时: {}分",minute);
                    }
                }else if(monitor.timeUnit() == Monitor.TimeUnit.HOUR){
                    double hour = ((int)((useTime/3600.0)*10)/10.0);
                    if (hour >= monitor.maxTime()){
                        log.info(monitor.value()+",用时: {}时",hour);
                    }
                }
            } else {
                log.info(monitor.value()+",用时: {}毫秒",(System.currentTimeMillis() -startTime));
            }
        }
    }

    /**
     * 获取当前切面执行的方法的方法名
     *
     * @param point 当前切面执行的方法
     */
    private Method getMethod(JoinPoint point) throws NoSuchMethodException {
        Signature sig = point.getSignature();
        MethodSignature msig = (MethodSignature) sig;
        Object target = point.getTarget();
        return target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
    }
}
